import EventRoute from "./EventRoute"
import {BrowserWindow, desktopCapturer} from "electron";
import RegionFrame from "../frames/RegionFrame";
import ScreenShotFrame from "../frames/ScreenShotFrame";
import os from 'os'
import fs from 'fs';
import path from 'path';

const routers = new Array();

let regionWindow = null, screenshotWindow = null;

/**
 * 选择区域
 */
routers.push(
  new EventRoute('select-region', 'event', (api, data = {}) => {
    if(regionWindow == null || regionWindow.getWindow() == null){
      regionWindow = new RegionFrame()
      regionWindow.show();
    }
  })
)

/**
 * 选择区域
 */
routers.push(
  new EventRoute('select-region-finished', 'event', (api, data = {}) => {
    const window = regionWindow.getWindow()
    const bounds = window.getBounds();
    // 使窗体始终在最上面
    // window.setAlwaysOnTop(true)
    // 鼠标可以穿透窗体点击
    window.setIgnoreMouseEvents(true)

    api.window.getWebContents().send('main-to-renderer', {
      name: 'did-region-finished',
      event: 'event',
      data: bounds
    })
  })
)

/**
 * 截图
 */
routers.push(
  new EventRoute('open-screenshot', 'event', (api, data = {}) => {
    if(screenshotWindow == null || screenshotWindow.getWindow() == null){
      screenshotWindow = new ScreenShotFrame()
      screenshotWindow.show();
    }
  })
)

/**
 * 关闭屏幕截图
 */
routers.push(
  new EventRoute('close-screenshot', 'event', (api, data = {}) => {
    const window = screenshotWindow.getWindow()
    window.close()
    window.destroy()
    screenshotWindow = null
  })
)

/**
 * 完成屏幕截图
 */
routers.push(
  new EventRoute('finished-screenshot-copy', 'event', (api, data = {}) => {
    const rectangle = data.data
    const {width, height} = api.screen.getPrimaryDisplay().size;

    const window = screenshotWindow.getWindow()
    // 开始截图
    api.capturer.getSources({ types: ['screen'] , thumbnailSize: {width: width, height: height}}).then(async sources => {
      for (const source of sources) {
        if(source.id === 'screen:0:0'){
          try{
            const image = source.thumbnail.crop(rectangle)
            api.clipboard.writeImage(image)
          }catch (e){
            console.log(e)
          }finally {
            // 关闭窗体
            window.close()
            window.destroy()
            screenshotWindow = null
          }
        }
      }
    })
  })
)

/**
 * 完成屏幕截图
 */
routers.push(
  new EventRoute('finished-screenshot-save', 'event', (api, data = {}) => {
    const rectangle = data.data
    const {width, height} = api.screen.getPrimaryDisplay().size;
    const window = screenshotWindow.getWindow()
    // 开始截图
    api.capturer.getSources({ types: ['screen'] , thumbnailSize: {width: width, height: height}}).then(async sources => {
      for (const source of sources) {
        if(source.id === 'screen:0:0'){
          try{
            const filename = new Date().getTime();
            api.dialog.showSaveDialog(window, {
              title: "请选择保存位置...",
              defaultPath: path.format({dir: os.homedir() + "\\Desktop\\", base: "DS截图_" + filename + ".png"})
            }).then(result => {
              if (result.filePath) {
                const image = source.thumbnail.crop(rectangle)
                fs.writeFileSync(result.filePath, image.toPNG());
              }
            })
          }catch (e){
            console.log(e)
          }finally {
            // 关闭窗体
            window.close()
            window.destroy()
            screenshotWindow = null
          }
        }
      }
    })
  })
)


routers.push(
  new EventRoute('start-record', 'event', (api, data = {}) => {
    const {width, height} = api.screen.getPrimaryDisplay().size;

    const region = data.data.region

    const webContents = api.window.getWebContents()
    api.capturer.getSources({ types: ['window', 'screen'] , thumbnailSize: {width: width, height: height}}).then(async sources => {
      for (const source of sources) {
        if(region == 'screen'){
          if (source.id === 'screen:0:0') {
            webContents.send('main-to-renderer', {
              name: 'start-recording',
              event: 'event',
              data: {
                sourceID: source.id,
                saveDir: api.app.getPath('videos')
              }
            })
          }
        }else if(region == 'window'){
          const window = regionWindow.getWindow()
          if (source.name.startsWith('dreamer-screen')) {
            webContents.send('main-to-renderer', {
              name: 'start-recording',
              event: 'event',
              data: {
                sourceID: window.getMediaSourceId(),
                saveDir: api.app.getPath('videos')
              }
            })
          }
        }
      }
    })
  })
)

routers.push(
  new EventRoute('stop-record', 'event', (api, data = {}) => {
    const window = regionWindow.getWindow()
    window.destroy()
    regionWindow = null
  })
)

// 打开外部URL
routers.push(
  new EventRoute('open-external-url', 'event', (api, data = {}) => {
    const url = data.data
    api.shell.openExternal(url)
  })
)

/**
 * 最小化应用
 */
routers.push(
  new EventRoute('app-minimize', 'event', (api, data = {}) => {
    const windows = BrowserWindow.getAllWindows()
    for (let i = 0; i < windows.length; i++) {
      windows[i].minimize()
    }
  })
)

/**
 * 退出应用
 */
routers.push(
  new EventRoute('app-quit', 'event', (api, data = {}) => {
    api.app.quit()
  })
)

export default routers
